import { makeRequiredRule } from '../../../utils'
import { regionData } from 'element-china-area-data'
const label = '地区'
const name = 'address'
let i = 1
const uniqueId = () => `${name}${i++}`
const box = {
  //拖拽组件的名称
  label,
  //拖拽组件的 key
  name,
  //拖拽组件的生成规则
  rule() {
    //如果在 props 方法中需要修改 rule 的属性,需要提前在 rule 上定义对应的属性
    return {
      type: 'cascader',
      field: uniqueId(),
      title: label,
      props: {
        options: regionData
      },
      control: [
        {
          handle: () => true,
          rule: [
            {
              type: 'input',
              field: uniqueId(),
              title: '详细地址',
              props: {
                placeholder: '请输入'
              },
              hidden: true,
              update(val, rule, fApi) {
                const parentField = rule.field.replace(
                  /\d+$/,
                  val => Number(val) - 1
                )
                const parent = fApi.getRule(parentField)
                if (
                  parent.$required !== false &&
                  parent.$required !== undefined
                ) {
                  rule.$required = '请输入详细地址'
                } else {
                  rule.$required = false
                }
              }
            }
          ]
        }
      ]
    }
  },
  //拖拽组件配置项(props)的生成规则
  props() {
    return [
      //生成`checkbox`组件的`options`配置规则
      {
        type: 'input',
        field: 'formCreateTitle',
        value: label,
        title: '字段名称'
      },
      {
        type: 'input',
        field: 'placeholder',
        title: '提示文字',
        value: '请选择'
      },
      {
        type: 'select',
        field: 'info',
        title: '地址经纬',
        value: true,
        options: [
          { value: true, label: '省/地区、市、区/县' },
          { value: false, label: '省/地区、市、区/县、详细地址' }
        ],
        update(val, _, fApi) {
          fApi.nextTick(() => {
            try {
              if (fApi.activeRule.control) {
                fApi.activeRule.control[0].rule[0].hidden = val
              }
            } catch (e) {}
          })
        }
      },
      makeRequiredRule()
    ]
  }
}
export default box
